package com.boss.example.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.boss.example.entity.vo.UserVO;
import com.boss.example.entity.dto.UserDTO;
import org.springframework.beans.BeanUtils;

@WebFilter(filterName = "UserLoginFilter",urlPatterns = "/user/*")
public class UserLoginFilter implements Filter {

    /**
     * 对Filter初始化
     * @param arg0
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    /**
     * 在Filter被销毁前回收某些资源
     */
    @Override
    public void destroy() {
    }

    /**
     * 判断用户是否登陆
     * @param arg0
     * @param arg1
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
                         FilterChain chain) throws IOException, ServletException {

        //获取用户访问的uri(统一资源标识符)
        HttpServletRequest req=(HttpServletRequest) arg0;
        String uri = req.getRequestURI();
        //System.out.println(uri);

        //判断当前访问的uri是否是用户登陆资源，如果是则放行
        //indexOf：比较uri这个字符串中是否存在login字符串。-1为indexOf的返回值，返回不到返回-1
        if (uri.indexOf("login")!=-1 || uri.indexOf("userlogin")!= -1) {
            chain.doFilter(arg0, arg1);
        }else {
            //用户是否登录的判断
            HttpSession session = req.getSession();
            UserVO userVO = (UserVO)session.getAttribute("user");
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(userVO,userDTO);
            if (userVO!=null && userDTO.getUsername().length()>0) {
                chain.doFilter(arg0, arg1);//放行
            }else {
                req.setAttribute("msg", "请登录");
                req.getRequestDispatcher("/login").forward(arg0, arg1);
            }
        }
    }

}
